﻿using Demo.Model.Other;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Model.Dto.User;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using SqlSugar;
using Demo.Model.Entitys;
using Demo.Model.Dto.User;
using Demo.Interface.BasicData;

namespace Demo.Service.BasicData
{
    public class CustomJWTService : ICustomJWTService
    {
        private readonly JWTTokenOptions _JWTTokenOptions;
        private readonly IRedis _redis;
        private readonly ISqlSugarClient _sqlSugarClient;

        public CustomJWTService(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions, IRedis redis, ISqlSugarClient sqlSugarClient)
        {
            _JWTTokenOptions = jwtTokenOptions.CurrentValue;
            _redis = redis;
            _sqlSugarClient = sqlSugarClient;
        }


        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public string GetToken(UserRes user)
        {
            #region 有效载荷，爱写多少写多少；尽量避免敏感信息
            var claims = new[]
            {
                    new Claim("Name",user.Name),
                    new Claim("Id",user.Id.ToString()),
                    new Claim("NickName",user.NickName),
                    new Claim("Name",user.Name),
                    new Claim("UserType",user.UserType.ToString()),
                    new Claim("Startdate",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    new Claim("Enddate",DateTime.Now.Add(TimeSpan.FromMinutes(_JWTTokenOptions.GqTime)).ToString("yyyy-MM-dd HH:mm:ss"))
            };
            //需要加密：需要加密key:
            //Nuget引入：Microsoft.IdentityModel.Tokens
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey));

            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //Nuget引入：System.IdentityModel.Tokens.Jwt
            JwtSecurityToken token = new JwtSecurityToken(
                 issuer: _JWTTokenOptions.Issuer,
                 audience: _JWTTokenOptions.Audience,
                 claims: claims,
                 expires: DateTime.Now.AddMinutes(_JWTTokenOptions.GqTime),//分钟计算
                 signingCredentials: creds
             );

            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            //将返回的token存入redis
            _redis.SetAsync("Zhao_" + user.Name, returnToken, DateTime.Now.AddMinutes(_JWTTokenOptions.GqTime * 2));


            return "Bearer  " + returnToken;
            #endregion
        }

        public UserList GetUsers(UserLogin userLogin)
        {
            var list = _sqlSugarClient.Queryable<UserList>().First(u => u.Name == userLogin.Name);
            return list;
        }
    }
}
